package io.dataease.utils;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
public class DateUtils {

    public static String time2String(Long time, String pattern) {
        if (StringUtils.isBlank(pattern)) pattern = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter format = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime timeByMilli = Instant.ofEpochMilli(time).atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        return format.format(timeByMilli);
    }
    public static String time2String(Long time) {
        String pattern = "yyyy-MM-dd HH:mm:ss";
        return time2String(time, pattern);
    }
    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }
    /**
     * 计算两个日期相差分钟数
     * @param date1
     * @param date2
     * @return
     */
    public static long differentMinutes(Date date1, Date date2) {
        long diffInMillies = Math.abs(date2.getTime() - date1.getTime());
        return TimeUnit.MILLISECONDS.toMinutes(diffInMillies);
    }
    /**
     * 当前时间加上指定的分钟数，返回新的时间
     * @param date 当前时间
     * @param minutes 指定的分钟数
     * @return 新的时间
     */
    public static Date addMinutes(Date date, int minutes) {
        Instant instant = date.toInstant();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        LocalDateTime newLocalDateTime = localDateTime.plus(minutes, ChronoUnit.MINUTES);
        return Date.from(newLocalDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }
    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }
}
